//
//  InviteViewController.m
//  Marketing
//
//  Created by HanenDev on 16/2/25.
//  Copyright © 2016年 Hanen 3G 01. All rights reserved.
//

#import "InviteViewController.h"
#import "JudgeNumber.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "SetButton.h"

#define STARTX [UIView getWidth:10]

@interface InviteViewController ()<UITextFieldDelegate,ABPeoplePickerNavigationControllerDelegate>
{
    UITextField *_phoneTF;
    UITextField *_nameTF;
    UISwitch    *swit;
    BOOL   isInvite;
}
@end

@implementation InviteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = graySectionColor;
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.titleView =  [ViewTool getNavigitionTitleLabel:@"邀请"];
    self.navigationItem.leftBarButtonItem=[ViewTool getBarButtonItemWithTarget:self WithAction:@selector(goToBack)];
    
    [self createUI];
    [self addBottomBtn];
}
- (void)createUI{
    
    
    CGFloat labelH =20;
    CGFloat space = 20;
    CGFloat labY = 15;
    
    
//    UIView *line1 = [ViewTool getLineViewWith:CGRectMake(0, space -1, KSCreenW, 1) withBackgroudColor:grayLineColor];
//    [self.view addSubview:line1];
    
    UIView *staffView = [ViewTool getLineViewWith:CGRectMake(0, space, KSCreenW, 2*(labelH + 2*labY)) withBackgroudColor:[UIColor whiteColor]];
    [self.view addSubview:staffView];
    
    UIView *line222 = [ViewTool getLineViewWith:CGRectMake(0, 0, KSCreenW, 1) withBackgroudColor:grayLineColor];
    [staffView addSubview:line222];
    
    //员工姓名
    UILabel *phoneLabel = [ViewTool getLabelWith:CGRectMake(STARTX, labY, 60, labelH) WithTitle:@"员工姓名" WithFontSize:13.0f WithTitleColor:grayFontColor WithTextAlignment:NSTextAlignmentLeft];
    [ViewTool setLableFont13:phoneLabel];
    [staffView addSubview:phoneLabel];
    
    _nameTF = [self addTextFieldWithFrame:CGRectMake(phoneLabel.maxX +10, phoneLabel.y, KSCreenW -STARTX - phoneLabel.width, labelH) AndStr:@"请填写姓名(必填)" AndFont:14.0f AndTextColor:blackFontColor];
    [_nameTF setValue:placeholderGrayFontColor forKeyPath:@"_placeholderLabel.textColor"];
    [_nameTF setValue:[UIFont systemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];
    [staffView addSubview:_nameTF];
    
    UIView *line2 = [ViewTool getLineViewWith:CGRectMake(STARTX, _nameTF.maxY + labY -1, KSCreenW - STARTX, 1) withBackgroudColor:grayLineColor];
    [staffView addSubview:line2];
    
    //员工号码
    UILabel *nameLabel = [ViewTool getLabelWith:CGRectMake(STARTX, line2.maxY + labY, 60, labelH) WithTitle:@"员工号码" WithFontSize:13.0f WithTitleColor:grayFontColor WithTextAlignment:NSTextAlignmentLeft];
    [ViewTool setLableFont13:nameLabel];
    [staffView addSubview:nameLabel];
    
    _phoneTF = [self addTextFieldWithFrame:CGRectMake(nameLabel.maxX +10, nameLabel.y, KSCreenW - nameLabel.width - STARTX, labelH) AndStr:@"请填写手机号(必填)" AndFont:14.0f AndTextColor:blackFontColor];
    _phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    [_phoneTF setValue:placeholderGrayFontColor forKeyPath:@"_placeholderLabel.textColor"];
    [_phoneTF setValue:[UIFont systemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];
    [staffView addSubview:_phoneTF];
    
    UIView *line3 = [ViewTool getLineViewWith:CGRectMake(0, _phoneTF.maxY + labY -1, KSCreenW, 1) withBackgroudColor:grayLineColor];
    [staffView addSubview:line3];
    
    UIView *line4 = [ViewTool getLineViewWith:CGRectMake(0, staffView.maxY + space -1, KSCreenW, 1) withBackgroudColor:grayLineColor];
    [self.view addSubview:line4];
    
    //添加手机联系人
    UIView *contactView = [ViewTool getLineViewWith:CGRectMake(0, line4.maxY , KSCreenW, (2*labY + labelH)) withBackgroudColor:[UIColor whiteColor]];
    [self.view addSubview:contactView];
    
    SetButton *addContactBtn = [[SetButton alloc]initWithFrame:CGRectMake((KSCreenW - 125)/2, 15, 125, contactView.height -30)];
    [addContactBtn setTitle:@"添加手机联系人" forState:UIControlStateNormal];
    [addContactBtn setImage:[UIImage imageNamed:@"HY_list_icon_add"] forState:UIControlStateNormal];
    [addContactBtn setTitleColor:greenBackColor forState:UIControlStateNormal];
    addContactBtn.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    [addContactBtn addTarget:self action:@selector(addContactPeople:) forControlEvents:UIControlEventTouchUpInside];
    [contactView addSubview:addContactBtn];
    
    SetButton *button = [[SetButton alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, contactView.height)];
//    button.backgroundColor = [UIColor redColor];
    button.userInteractionEnabled = YES;
    [button addTarget:self action:@selector(addContactPeople:) forControlEvents:UIControlEventTouchUpInside];
    [contactView addSubview:button];
    
    
    UIView *line5 = [ViewTool getLineViewWith:CGRectMake(0, contactView.height - 1, KSCreenW, 1) withBackgroudColor:grayLineColor];
    [contactView addSubview:line5];
    
    UIView *line6 = [ViewTool getLineViewWith:CGRectMake(0, contactView.maxY + space -1, KSCreenW, 1) withBackgroudColor:grayLineColor];
    [self.view addSubview:line6];
    
    //是否短信通知
    UIView *inviteView = [ViewTool getLineViewWith:CGRectMake(0, line6.maxY , KSCreenW, (2*labY + labelH)) withBackgroudColor:[UIColor whiteColor]];
    [self.view addSubview:inviteView];
    
    UILabel *inviteLabel = [ViewTool getLabelWith:CGRectMake(STARTX, labY, KSCreenW - 2*STARTX  - 50, labelH) WithTitle:@"短信通知ta加入企业应用" WithFontSize:14.0f WithTitleColor:UIColorFromRGB(0x8c8c8c) WithTextAlignment:NSTextAlignmentLeft];
    [inviteView addSubview:inviteLabel];
    
    
    swit = [[UISwitch alloc]initWithFrame:CGRectMake(KSCreenW - 50 -STARTX, 10, 30, 20)];
    [swit addTarget:self action:@selector(switchIsChanged:) forControlEvents:UIControlEventValueChanged];
    swit.onTintColor = UIColorFromRGB(0x00c6ae);
    [swit setOn:NO animated:YES];
    [inviteView addSubview:swit];
    if (swit.isOn) {
        isInvite = YES;
    }else{
        isInvite = NO;
    }
    
    UIView *line7 = [ViewTool getLineViewWith:CGRectMake(0, inviteView.height -1, KSCreenW, 1) withBackgroudColor:grayLineColor];
    [inviteView addSubview:line7];
    
    UILabel *explainLabel = [[UILabel alloc]initWithFrame:CGRectMake(STARTX, inviteView.maxY-2, KSCreenW - 2*STARTX, labelH*2)];
    explainLabel.text = @"若开启,系统将自动发送短信邀请对方加入(此短信免费)";
    explainLabel.textColor = UIColorFromRGB(0xa3a3a3);
    explainLabel.font = [UIFont systemFontOfSize:12.0f];
    explainLabel.numberOfLines = 0;
    [self.view addSubview:explainLabel];
    
}
- (void)addBottomBtn{
    
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, KSCreenH - 70 -64, KSCreenW, 70)];
    footerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:footerView];
    
    UIButton *referBtn = [[UIButton alloc]initWithFrame:CGRectMake(13, 8, footerView.width - 20, footerView.height - 10)];
    [referBtn setTitle:@"确认提交" forState:UIControlStateNormal];
    [referBtn setBackgroundImage:[UIImage imageNamed:@"HY_btn_red_normal.png"] forState:UIControlStateNormal];
    [referBtn setBackgroundImage:[UIImage imageNamed:@"HY_btn_red_press.png"] forState:UIControlStateHighlighted];
    [referBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [referBtn addTarget:self action:@selector(referInvitation:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:referBtn];
    
    UIView *line3 = [ViewTool getLineViewWith:CGRectMake(0, 0, KSCreenW, 1) withBackgroudColor:grayLineColor];
    [footerView addSubview:line3];
    
    
}
#pragma mark
#pragma  mark-----添加手机联系人
- (void)addContactPeople:(SetButton *)btn{
    
        ABAddressBookRef addressBook = nil;
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
            addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
            //等待同意后向下执行
            dispatch_semaphore_t sema = dispatch_semaphore_create(0);
            ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
                dispatch_semaphore_signal(sema);
                NSLog(@"这里是用户选择是否允许后的执行代码");
                
                ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc] init];
                peoplePicker.peoplePickerDelegate = self;
                [self presentViewController:peoplePicker animated:YES completion:nil];
                
            });
        }
        else{
            addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
        }
    
}
//iOS8
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFTypeRef firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
    CFTypeRef lastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
    //姓
    NSString * nameString;
    if (firstName != nil) {
        nameString = (__bridge NSString *)firstName;
    }else{
        nameString = @"";
    }
    
    //名
    NSString * lastString;
    if (lastName != nil) {
        lastString = (__bridge NSString *)lastName;
    }else{
        lastString = @"";
    }
    long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
    NSString *phoneNum = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
    
    if ([phoneNum hasPrefix:@"+"]) {
        phoneNum = [phoneNum substringFromIndex:3];
    }
    
    phoneNum = [phoneNum stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSLog(@"%@", phoneNum);
    if (phone) {
        _phoneTF.text = phoneNum;
        _nameTF.text = [NSString stringWithFormat:@"%@%@",lastString,nameString];
        [peoplePicker dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    
    
}

//iOS7
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person{
    
    return YES;
}

//iOS7
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFTypeRef firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
    CFTypeRef lastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
    //姓
    NSString * nameString;
    if (firstName != nil) {
        nameString = (__bridge NSString *)firstName;
    }else{
        nameString = @"";
    }
    
    //名
    NSString * lastString;
    if (lastName != nil) {
        lastString = (__bridge NSString *)lastName;
    }else{
        lastString = @"";
    }
    
    long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
    NSString *phoneNum = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
    if ([phoneNum hasPrefix:@"+"]) {
        phoneNum = [phoneNum substringFromIndex:3];
    }
    phoneNum = [phoneNum stringByReplacingOccurrencesOfString:@"-" withString:@""];
    if (phone) {
        _phoneTF.text = phoneNum;
        _nameTF.text = [NSString stringWithFormat:@"%@%@",lastString,nameString];
        [peoplePicker dismissViewControllerAnimated:YES completion:nil];
        return NO;
    }
    return YES;
}
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark
#pragma  mark-----提交邀请
- (void)referInvitation:(UIButton *)btn{
    if (_nameTF.text == nil | [_nameTF.text length] == 0 ){
        [self.view makeToast:@"请填写姓名"];
        return;
    }else if (_phoneTF.text == nil | [_phoneTF.text length] == 0 ){
        [self.view makeToast:@"请输入手机号码"];
        return;
    }else if (![JudgeNumber boolenPhone:_phoneTF.text]){
        [self.view makeToast:@"请输入正确手机号"];
        return;
    }
    NSString *doMessage;
    if (isInvite) {
        doMessage = @"true";
    }else{
        doMessage = @"false";
    }
    NSNumber *departmentID = [NSNumber numberWithInt:1];
    NSDictionary * dic =@{@"token":TOKEN,@"uid":@(UID),@"username":_phoneTF.text,@"name":_nameTF.text,@"department":departmentID,@"doMessage":doMessage};
    [DataTool postWithUrl:INVITE_STUFF_URL parameters:dic success:^(id data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",jsonDic);
        int code = [jsonDic[@"code"] intValue];
        if (code == 100) {
            [self.view makeToast:@"邀请成功"];
            
            [self performSelector:@selector(tipToInvite) withObject:nil afterDelay:1];
            
        }else{
            NSString *message = jsonDic[@"message"];
            [self.view makeToast:message];
            
        }
        
    } fail:^(NSError *error) {
        NSLog(@"%@+++++++++",error);
    }];
    
}
- (void)tipToInvite{
    [self.navigationController popViewControllerAnimated:YES];
}
//开关
- (void)switchIsChanged:(UISwitch *)swit{
    if (isInvite) {
        isInvite = NO;
    }else{
        isInvite = YES;
    }
    
}

-(UITextField *)addTextFieldWithFrame:(CGRect)frame AndStr:(NSString *)placeholder AndFont:(CGFloat)font AndTextColor:(UIColor *)color
{
    UITextField *textF=[[UITextField alloc]initWithFrame:frame];
    textF.userInteractionEnabled = YES;
    textF.textColor = color;
    textF.font =[UIFont systemFontOfSize:font];
    textF.placeholder=placeholder;
    textF.delegate = self;
    [ViewTool setTFPlaceholderFont14:textF];
    return textF;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [_nameTF resignFirstResponder];
    [_phoneTF resignFirstResponder];
}
- (void)goToBack{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.hidesBottomBarWhenPushed = NO;
}

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.hidesBottomBarWhenPushed = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
